package com.meng.android.util;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import android.util.Log;

public class BeanUtils {

	private static final String LOG_CAT = "com.meng.android.util.BeanUtils";

	public static void setProperty(Object obj, String fieldName, Object value) {
		Log.i(LOG_CAT, "start object reflection");
		Log.i(LOG_CAT, "obj " + obj.getClass());
		Log.i(LOG_CAT, "fieldName " + fieldName);
		Log.i(LOG_CAT, "value " + value.getClass());
		Log.i(LOG_CAT, "---------------------------");

		try {
			Class<?> clazz = obj.getClass();
			Field field = clazz.getDeclaredField(fieldName);
			Log.i(LOG_CAT, "field class type " + field.getType());
			Log.i(LOG_CAT, "field class generic type " + field.getGenericType());
			field.setAccessible(true);
			field.set(obj, value);
		} catch (NoSuchFieldException e) {
			// clazz = clazz.getSuperclass();
		} catch (Exception e) {
			Log.e(LOG_CAT, fieldName, e);
		}
	}

	public static void setProperty(Object obj, Map<String, Object> values) {
		Iterator entries = values.entrySet().iterator();
		while (entries.hasNext()) {
			Entry thisEntry = (Entry) entries.next();
			Object key = thisEntry.getKey();
			Object value = thisEntry.getValue();
			setProperty(obj, (String) key, value);
		}
	}

	public static Object getProperty(Object obj, String fieldName) {
		Class<?> clazz = obj.getClass();
		try {
			Field f = clazz.getDeclaredField(fieldName);
			f.setAccessible(true);
			Object res = f.get(obj);

			Log.i(LOG_CAT, "f.getGenericType(): " + f.getGenericType());
			Log.i(LOG_CAT, "f.getType(): " + f.getType());
			Log.i(LOG_CAT, "f.getType(): " + f.getType());
			Log.i(LOG_CAT, "res: " + res);

			return res;
		} catch (NoSuchFieldException e) {
			Log.e(LOG_CAT, "Error: ", e);
		} catch (IllegalAccessException e) {
			Log.e(LOG_CAT, "Error: ", e);
		} catch (IllegalArgumentException e) {
			Log.e(LOG_CAT, "Error: ", e);
		}
		return null;
	}
}